package com.ruoyi.service.impl;


import com.ruoyi.gisconverter.core.ConvertProcess;
import com.ruoyi.gisconverter.ext.ExtensionsUtil;
import com.ruoyi.gisconverter.ext.FileExtension;

import com.ruoyi.myutils.ShpGeoJsonConverter;
import com.ruoyi.myutils.ShpToWktConverter;
import com.ruoyi.myutils.UtilsWuda;
import com.ruoyi.service.AddDataService;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.io.FilenameUtils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

import static com.ruoyi.myutils.UtilsWuda.deleteTempFiles;

@Slf4j
@Service
public class AddDataServiceImpl implements AddDataService {


    @Value("${file.shpFile}")
    private String shpFile;

    private int ScanSuffixCount = 0;

    private ArrayList<String> ScanSuffixFiles = new ArrayList<String>();

    @Override
    public String addGeoJsonFile(MultipartFile geoJsonFile) {
        String wktMerge ="";
        File inputFile = null;
        try {
            // 创建输出格式
            ExtensionsUtil extUtil = new ExtensionsUtil();
            FileExtension outputFormat = extUtil.getFileExtension("shp");
            // 指定输入文件
            inputFile = UtilsWuda.convertMultipartFileToFile(geoJsonFile);
            // 执行转换
            ConvertProcess p = new ConvertProcess(new File(inputFile.getAbsolutePath()), outputFormat);
            p.execute();

            System.out.println("转换完成！输出文件: " +
                    FilenameUtils.removeExtension(inputFile.getAbsolutePath()) + ".shp");

            String pathWithoutExtension = FilenameUtils.removeExtension(inputFile.getAbsolutePath()); //直接去除后缀
            System.out.println(pathWithoutExtension + ".shp");
            //转化为坐标系为4326的wkt
            wktMerge = ShpGeoJsonConverter.Shp2GeoJson(pathWithoutExtension + ".shp").toString();

        } catch (Exception e) {
            System.err.println("失败: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 删除临时文件
            deleteTempFiles(inputFile);
        }
        return  wktMerge;
    }

    @Override
    public String addShpFile(MultipartFile[] shpFiles) {
        String wktMerge = ShpToWktConverter.multipartFileShp2Wkt(shpFiles).toString();
        return wktMerge;
    }



}


